package com.ebeitech.doorapp.view;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.RemoteViews;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.http.EbeiErrorCode;
import com.ebeitech.doorapp.http.HttpListener;
import com.ebeitech.doorapp.http.HttpService;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.StringUtil;

import java.io.File;

/**
 * Created by alice on 2018/1/25.
 */
public class VersionService  extends Service {

	private static float loading_process;
	private NotificationManager notificationMrg;
	private float old_process = 0;
	private boolean isRefresh = false;
	private String mUrl;

	public void onCreate() {
		super.onCreate();
		notificationMrg = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent != null) {
			mUrl = intent.getStringExtra("url");
			if (StringUtil.isStringNullOrEmpty(mUrl)) {
				return super.onStartCommand(intent, flags, startId);
			}
			if ("stop".equals(intent.getAction())) {
				mHandler.sendEmptyMessage(-1);
				return super.onStartCommand(intent, flags, startId);
			}
			String filePath = CommonUtil.getCacheFile(getApplicationContext(), "apk") + File.separator + "app.apk";
			HttpService.getInstance().downloadFile(getApplicationContext(), new HttpListener<String>() {
				@Override
				public void onStart() {

				}

				@Override
				public void onError(EbeiErrorCode errorCode) {
					mHandler.sendEmptyMessage(-1);
				}

				@Override
				public void onSuccess(String result) {
					if (loading_process < 98) {
						loading_process = 98;
						mHandler.sendEmptyMessage(0);
					}
					loading_process = 100;
					mHandler.sendEmptyMessage(-1);
				}
			}, new HttpService.HttpLoadListener() {
				@Override
				public void onLoad(float progress) {
					loading_process = progress;
					if (loading_process > old_process && isRefresh) {
						isRefresh = false;
						mHandler.sendEmptyMessage(0);
					}
				}
			}, mUrl, filePath);
			mHandler.sendEmptyMessage(0);
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private Handler mHandler = new Handler(Looper.getMainLooper()) {
		@Override
		public void handleMessage(Message msg) {
			// 1为出现，2为隐藏
			if(loading_process>99 || msg.what == -1){
				if (loading_process > 99) {
					String fileName = mUrl;
					if (fileName.contains("/")) {
						String fileNameT = fileName.substring(fileName.lastIndexOf("/"));
						if (fileNameT.length() > 0) {
							fileName = fileNameT.substring(1);
						}
					}
					String filePath = CommonUtil.getExternalCacheFile(getApplicationContext()) + File.separator + fileName;
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.setDataAndType(Uri.fromFile(new File(filePath)),
							"application/vnd.android.package-archive");
					startActivity(intent);
				}
				notificationMrg.cancel(0);
				loading_process = 0;
				old_process = 0;
				stopSelf();
				return;
			}

			displayNotificationMessage(loading_process);
			isRefresh = true;
			old_process = loading_process;
		}
	};

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	private void displayNotificationMessage(float count) {

		// Notification的Intent，即点击后转向的Activity
		Intent notificationIntent1 = new Intent(this, this.getClass());
		notificationIntent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent contentIntent1 = PendingIntent.getActivity(this, 0,
				notificationIntent1, 0);

		// 创建Notifcation
		Notification notification = new Notification(R.mipmap.ebei_ic_launcher,
				"tickerText1", System.currentTimeMillis());// 设定Notification出现时的声音，一般不建议自定义
		if(loading_process>97){
			notification.defaults |= Notification.DEFAULT_SOUND;// 设定是否振动
			notification.defaults |= Notification.DEFAULT_VIBRATE;
		}notification.flags |= Notification.FLAG_ONGOING_EVENT;

		// 创建RemoteViews用在Notification中
		RemoteViews contentView = new RemoteViews(getPackageName(),
				R.layout.ebei_notification_version);
		contentView.setTextViewText(R.id.n_title, "升级提示");
		contentView.setTextViewText(R.id.n_text, "当前进度："+count+"% ");
		contentView.setProgressBar(R.id.n_progress, 100, (int)count, false);

		notification.contentView = contentView;
		notification.contentIntent = contentIntent1;

		notificationMrg.notify(0, notification);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}
